import { useFrame } from '@react-three/fiber';
import React, { useRef } from 'react';

import Flower from '../Flower';
import Tree from '../Tree';

const treeCount = 300;
const trees: React.ReactNode[] = [];
const stepAngle1 = (Math.PI * 2) / treeCount;
const h = 605;

for (let i = 0; i < treeCount; i++) {
  const a = stepAngle1 * i;
  const x = Math.cos(a) * h;
  const y = Math.sin(a) * h;
  const z = -Math.random() * 600;
  const s = 0.3 + Math.random() * 0.75;
  trees.push(<Tree key={i} position={[x, y, z]} rotation-z={a + (Math.PI / 2) * 3} scale={s} />);
}

const flowerCount = 350;
const flowers: React.ReactNode[] = [];
const stepAngle2 = (Math.PI * 2) / flowerCount;

for (let i = 0; i < flowerCount; i++) {
  const a = stepAngle2 * i;
  const y = Math.sin(a) * h;
  const x = Math.cos(a) * h;
  const z = -Math.random() * 600;

  flowers.push(
    <Flower
      key={i}
      position={[x, y, z]}
      rotation-z={a + (Math.PI / 2) * 3}
      scale={0.1 + Math.random() * 0.3}
    />,
  );
}

const Forest = () => {
  const land = useRef<THREE.Group>(null);
  useFrame((state, delta) => {
    if (land.current) {
      land.current.rotation.z += delta * 0.2;
    }
  });

  return (
    <group ref={land} position-y={-600}>
      {trees}
      {flowers}
    </group>
  );
};

export default Forest;
